/*
 * Copyright 2009-2010 Belmont Software Services
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.belmont.backup.gui;

import java.awt.Component;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.util.EventObject;

import javax.swing.AbstractCellEditor;
import javax.swing.JTree;
import javax.swing.event.ChangeEvent;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreePath;

/**
 * @author Jaffer
 *
 */
public class CheckBoxNodeEditor extends AbstractCellEditor implements TreeCellEditor {
    static final long serialVersionUID = 6750574748586409229L;
    CheckBoxNodeRenderer renderer = new CheckBoxNodeRenderer();
    ChangeEvent changeEvent = null;
    JTree tree;

    public CheckBoxNodeEditor(JTree tree) {
	this.tree = tree;
    }

    public Object getCellEditorValue() {
	BNRCheckBox checkbox = renderer.getLeafRenderer();
	return new CheckBoxNode(checkbox);
    }

    public boolean isCellEditable(EventObject event) {
	boolean returnValue = false;
	if (event instanceof MouseEvent) {
	    MouseEvent mouseEvent = (MouseEvent) event;
	    TreePath path = tree.getPathForLocation(mouseEvent.getX(), mouseEvent.getY());
	    if (path != null) {
		Object node = path.getLastPathComponent();
		if ((node != null) && (node instanceof DefaultMutableTreeNode)) {
		    DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) node;
		    Object userObject = treeNode.getUserObject();
		    returnValue = ((treeNode.isLeaf()) && (userObject instanceof CheckBoxNode));
		}
	    }
	}

	return returnValue;
    }

    public Component getTreeCellEditorComponent(JTree tree, Object value, boolean selected,
						boolean expanded,
						boolean leaf, int row) {
	Component editor = renderer.getTreeCellRendererComponent(tree, value, true, expanded, leaf, row, true);

	// editor always selected / focused
	ItemListener itemListener = new ItemListener() {
		public void itemStateChanged(ItemEvent itemEvent) {
		    if (stopCellEditing()) {
			fireEditingStopped();
		    }
		}
	    };

	if (editor instanceof BNRCheckBox) {
	    ((BNRCheckBox) editor).addItemListener(itemListener);
	}

	return editor;
    }
}